<template>
  <div class="home-page">
    <div class="left">
      <CartView :cartList="cart" @delGoodsFn="delGoodsFn" @clearCartFn="clearCartFn"/>
    </div>
    <div class="right">
      <div class="right-header">类别选择</div>
      <div class="right-body">
        <GoodsItem
          class="goods-item"
          @click.native="addCart(item)"
          v-for="item in goodsList"
          :key="item.id"
          :goodsDetail="item"
        />
      </div>
    </div>
  </div>
</template>

<script>
import CartView from '@/components/CartView.vue'
import GoodsItem from '@/components/GoodsItem.vue'
import axios from 'axios'
export default {
  components: {
    CartView,
    GoodsItem
  },
  data () {
    return {
      goodsList: [],
      cart: []
    }
  },
  created () {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList () {
      const { data } = await axios.get('http://localhost:3000/goodsList')
      this.goodsList = data
    },
    addCart (item) {
      const findGoods = this.cart.find(i => i.id === item.id)
      if (findGoods) {
        findGoods.count++
      } else {
        this.cart.push(item)
      }
    },
    delGoodsFn (id) {
      const findGoods = this.cart.find(i => i.id === id)
      console.log(findGoods)
      if (findGoods.count <= 1) {
        const index = this.cart.indexOf(findGoods)
        this.cart.splice(index, 1)
      } else {
        findGoods.count--
      }
    },
    clearCartFn () {
      this.cart = []
    }
  }
}
</script>

<style scoped lang="scss">
.home-page {
  display: flex;
  height: 100%;
  .left {
    flex: 1;
  }
  .right {
    flex: 3;
    .right-header {
      padding: 0 20px;
      height: 50px;
      font-size: 24px;
      line-height: 50px;
      background-color: #ace;
    }
    .right-body {
      padding: 0 0 4px 4px;
      display: flex;
      flex-wrap: wrap;
      .goods-item {
        margin: 5px 5px 0 0;
      }
    }
  }
}
</style>
